package com.sky.demo.file;

import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.ObjectUtil;

import java.io.IOException;
import java.nio.file.*;

/**
 * 监听配置文件变更
 */
public class WatchService {

    static java.nio.file.WatchService watchService = null;
    static String filename = null;
    static {

        try{

            filename = "application.properties";
            ClassPathResource resource = new ClassPathResource(filename);
            watchService = FileSystems.getDefault().newWatchService();
            Paths.get(resource.getFile().getParent())
                    .register(watchService,
                            StandardWatchEventKinds.ENTRY_MODIFY,
                            StandardWatchEventKinds.ENTRY_DELETE);
        } catch (IOException e){
            e.printStackTrace();
        }

        Thread watchThread = new Thread(()->{
            while(true){
                try{
                    WatchKey watchKey = watchService.take();
                    for(WatchEvent<?> event : watchKey.pollEvents()){
                        if(ObjectUtil.equal(event.context().toString(), filename)){
                            break;
                        }
                    }
                    watchKey.reset();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        watchThread.setDaemon(true);
        watchThread.start();


        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try{
                watchService.close();
            } catch (IOException e){
                e.printStackTrace();
            }
        }));
    }
}
